package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 *   实现订单转换实现的自动转换类
 * @description 输入映射 string--> Date  输出映射 Date --> String
 * @date        2022.04.07 16:34
 * @package     com.cskaoyan.typehandler
 * @Classname   String2DateTypeHandler
 * @author      rebaogu
 */
// java指定类型

// 数据库指定类型
@MappedTypes(String.class)
@MappedJdbcTypes(JdbcType.DATE)
public class String2DateTypeHandler implements TypeHandler<Date> {

    ObjectMapper objectMapper = new ObjectMapper();

    // 输入映射
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Date date, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(date);
        preparedStatement.setString(index, value);
    }


    // 输出映射
    @Override
    public Date getResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);

        return transfer(result);
    }


    @Override
    public Date getResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        return transfer(result);
    }

    @Override
    public Date getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        return transfer(result);
    }


    private Date transfer(String result) {
        if (result == null || "".equals(result)) {
            return null;
        }
        Date date = null;
        try {
            date = objectMapper.readValue(result, Date.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return date;
    }
}
